package com.smmisia.shop.model;

import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.smmisia.shop.constant.ProductStateEnum;
import com.smmisia.shop.constant.ProductVoState;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;

@Data
@Setter
@Getter
public class ProductVO implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 主键ID（自增主键）
     */
    private Long id;

    /**
     * 卖家id
     */
    private Long sellerId;
    /**
     * 商品名称
     */
    private String name;

    /**
     * 商品封面
     */
    private String cover;

    /**
     * 商品类目id
     */
    private String classId;

    /**
     * 商品图片
     */
    private String images;

    /**
     * 价格
     */
    private BigDecimal price;

    /**
     * 商品数量
     */
    private Long quantity;

    /**
     * 详情
     */
    private String detail;

    /**
     * 可销售库存
     */
    private Long saleableInventory;

    /**
     * 状态
     */
    private ProductVoState state;

    /**
     * 发售时间
     */
    private LocalDateTime saleTime;

    /**
     * 创建时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime createTime;

    public static final int DEFAULT_MIN_SALE_TIME = 60;

    public void setState(ProductStateEnum state, Date saleTime, Long saleableInventory) {
        if (state.equals(ProductStateEnum.INIT) || state.equals(ProductStateEnum.REMOVED)) {
            this.setState(ProductVoState.NOT_FOR_SALE);
        }

        Instant now = Instant.now();

        if (now.compareTo(saleTime.toInstant()) >= 0) {
            if (saleableInventory > 0) {
                this.setState(ProductVoState.SELLING);
            } else {
                this.setState(ProductVoState.SOLD_OUT);
            }
        } else {
            if (ChronoUnit.MINUTES.between(now, saleTime.toInstant()) > DEFAULT_MIN_SALE_TIME) {
                this.setState(ProductVoState.WAIT_FOR_SALE);
            } else {
                this.setState(ProductVoState.COMING_SOON);
            }
        }
    }
}
